//
//  CMSViewController.m
//  CMS
//
//  Created by Phan The Dung on 10/17/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CMSViewController.h"
#import "SBJson.h"
#import "ListViewControler.h"
#import "TableViewOnlineController.h"
#import "StoreVars.h"

@implementation CMSViewController
@synthesize imageViewLoginScreen = _imageViewLoginScreen;
@synthesize userNameLogin = _userNameLogin;
@synthesize passwordLogin = _passwordLogin;


- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"sendInfo"]){
        ListViewControler *listView = [segue destinationViewController];
        NSLog(@"Text: %@", self.passwordLogin.text); 
        listView.infoRequest = self.passwordLogin.text;
    }
    // set send bundle over nextView
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
    // Release any cached data,  , etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (IBAction)backgroundClicked:(id)sender {
    [_userNameLogin resignFirstResponder];
    [_passwordLogin resignFirstResponder];
}
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    
    [alertView show];
}
- (IBAction)btnLoginClicked:(id)sender {
    @try {
        
        if([[_userNameLogin text] isEqualToString:@""] || [[_passwordLogin text] isEqualToString:@""] ) {
            [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
        } else {
            NSString *post =[[NSString alloc] initWithFormat:@"uname=%@&pword=%@",[_userNameLogin text],[_passwordLogin text]];

            NSURL *url=[NSURL URLWithString:@"http://192.168.1.24:8888/services/login"];
            
            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            
            NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
            
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];
            [request setTimeoutInterval:15];
            
//            [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
            
            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            
            NSLog(@"Response code: %d", [response statusCode]);
            if ([response statusCode] >=200 && [response statusCode] <300)
            {
                NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];                 
                
                SBJsonParser *jsonParser = [SBJsonParser new];
                NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                NSInteger success = [(NSNumber *) [jsonData objectForKey:@"status"] integerValue];
                NSDictionary *errorDic = [jsonData objectForKey:@"data"];

                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                    //add  session id and user name to global variable                    
                    [StoreVars sharedInstance].sessionId = [errorDic objectForKey:@"session_id"];
                    [StoreVars sharedInstance].username = self.userNameLogin.text;
                    NSLog(@"sessionId: %@", [StoreVars sharedInstance].sessionId);
                    //create folder to store downloaded data from server
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
                    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
                    NSString *userFolder = [documentsDirectory stringByAppendingFormat:@"/%@", self.userNameLogin.text]; //get folder foreach user                                        
                    NSString *dataPath = userFolder;//[documentsDirectory stringByAppendingPathComponent:@"dataStore"];
                    
                    //Create folder
                    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
                        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
                    
                    //Store global variable download dir director
                    [StoreVars sharedInstance].downloadDir = dataPath;
                    
                    UIStoryboard *mainStorybroad = [UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil];
                    TableViewOnlineController *listView = [mainStorybroad instantiateViewControllerWithIdentifier:@"viewListContentOnline"];
                    [self.navigationController pushViewController:listView animated:YES];
                    
                } else {
                    NSString *error_msg = (NSString *) [errorDic objectForKey:@"error_code"];
                    [self alertStatus:error_msg :@"Login Failed!"];
                }
                
            } else {
//                if (error) NSLog(@"Error: %@", error);
                NSLog(@"Connect failed");
                [self alertStatus:@"Connection Failed" :@"Login Failed!"];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Login Failed. Please, contact with administrators to resolve!" :@"Login Failed!"];
    }
}

@end
